package scanner.impl;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import pojo.Customer;
import scanner.DataScanner;

public class DataScannerImpl implements DataScanner {
	private InputStream in;
	private Scanner scanner;
	
	public DataScannerImpl(InputStream inputStream) {
		// TODO Auto-generated constructor stub
		super();
		this.in = inputStream;
		scanner = new Scanner(in);
	}

	public List<Customer> scan() throws Exception {
		// TODO Auto-generated method stub
		List<String> list = checkout();
		List<Customer> customers = new ArrayList<Customer>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for(String string:list){
			String[] strings = string.split("\\s+");
			Customer customer = new Customer(Integer.parseInt(strings[0]), 
					strings[1], strings[2], Boolean.parseBoolean(strings[3]), sdf.parse(strings[4]));
			customers.add(customer);
		}
		return customers;
	}
	
	private List<String> checkout(){
		String re = "^([0-9]+)\\s+([a-zA-Z]+)\\s+(\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*)\\s+(true|false)\\s+(((19\\d{2})|(200\\d)|(201[0-7]))-((0?[1-9])|(1[0-2]))-((0?[1-9])|([1-2]\\d)|(30)))";
		List<String> list = new ArrayList<String>();
		while(scanner.hasNext()){
			String string = scanner.nextLine();
			Pattern pattern = Pattern.compile(re);
			Matcher matcher = pattern.matcher(string);
			if(matcher.find()){
				list.add(string);
			}
		}
		return list;
		
	}

}
